const express = require('express');
const router = express.Router();
const pool = require('./db');

// 收藏题目接口
router.post('/collect-question', async (req, res) => {
    try {
        const { practiceId, userId, questionOrder } = req.body;
        const tables = ['commited_choice_question', 'commited_fill_question', 'commited_essay_question'];

        for (const table of tables) {
            const [rows] = await pool.execute(
                `UPDATE ${table} SET is_collected = 1 WHERE practice_id = ? AND commit_user_id = ? AND question_order = ?`,
                [practiceId, userId, questionOrder]
            );
            if (rows.affectedRows > 0) {
                break;
            }
        }
        res.status(200).json({ message: '题目已收藏' });
    } catch (error) {
        console.error(error);
        res.status(500).json({ message: '收藏题目失败' });
    }
});

// 取消收藏题目接口
router.post('/uncollect-question', async (req, res) => {
    try {
        const { practiceId, userId, questionOrder } = req.body;
        const tables = ['commited_choice_question', 'commited_fill_question', 'commited_essay_question'];

        for (const table of tables) {
            const [rows] = await pool.execute(
                `UPDATE ${table} SET is_collected = 0 WHERE practice_id = ? AND commit_user_id = ? AND question_order = ?`,
                [practiceId, userId, questionOrder]
            );
            if (rows.affectedRows > 0) {
                break;
            }
        }
        res.status(200).json({ message: '题目已取消收藏' });
    } catch (error) {
        console.error(error);
        res.status(500).json({ message: '取消收藏题目失败' });
    }
});

// 检查题目是否被收藏
router.get('/check-question-collection', async (req, res) => {
    const { practiceId, userId, questionOrder } = req.query;
    const tables = ['commited_choice_question', 'commited_fill_question', 'commited_essay_question'];

    for (const table of tables) {
        const [rows] = await pool.execute(
            `SELECT is_collected FROM ${table} WHERE practice_id = ? AND commit_user_id = ? AND question_order = ?`,
            [practiceId, userId, questionOrder]
        );
        if (rows.length > 0) {
            return res.json({ isCollected: Boolean(rows[0].is_collected) });
        }
    }
    res.json({ isCollected: false });
});

// 获取用户收藏的题目信息
router.get('/api/user-collected-questions/:userId', async (req, res) => {
    const { userId } = req.params;
    try {
        // 依次检索选择题、填空题、解答题
        const [choiceQuestions] = await pool.execute(`
            SELECT 'choice' as question_type, practice_id, question_order
            FROM commited_choice_question
            WHERE commit_user_id = ? AND is_collected = 1
        `, [userId]);

        const [fillQuestions] = await pool.execute(`
            SELECT 'fill' as question_type, practice_id, question_order
            FROM commited_fill_question
            WHERE commit_user_id = ? AND is_collected = 1
        `, [userId]);

        const [essayQuestions] = await pool.execute(`
            SELECT 'essay' as question_type, practice_id, question_order
            FROM commited_essay_question
            WHERE commit_user_id = ? AND is_collected = 1

        `, [userId]);

        // 合并所有结果
        let allQuestions = [...choiceQuestions, ...fillQuestions, ...essayQuestions];

        allQuestions.sort((a, b) => {
            // 先比较练习ID（使用localeCompare确保字符串正确排序）
            const practiceCompare = a.practice_id.localeCompare(b.practice_id);
            if (practiceCompare !== 0) {
                return practiceCompare;
            }
            
            // 练习ID相同时，比较题目类型
            const typeOrder = { 'choice': 1, 'fill': 2, 'essay': 3 };
            return typeOrder[a.question_type] - typeOrder[b.question_type];
        });

        res.json(allQuestions);
    } catch (error) {
        console.error('Error getting user collected questions:', error);
        res.status(500).json({ 
            success: false,
            message: '获取用户收藏题目失败'
        });
    }
});
module.exports = router;